from django.shortcuts import render, get_object_or_404, redirect
from .models import Post
from .forms import PostForm

# Create your views here.
def post_list(request):
    ## 从数据库中获取所有的Post对象，并按创建时间倒序排列（新的在前）
    posts = Post.objects.filter(is_published=True).order_by('-created_at') #- 号表示降序
    ## 渲染模板，并将获取到的文章列表（posts）传递给模板
    return render(request, 'blog/post_list.html',{'posts': posts})

def post_detail(request, post_id):
    ## 根据传入的post_id获取对应的Post对象，如果不存在则返回404错误
    post = get_object_or_404(Post, id=post_id, is_published=True)
    ## 渲染模板，并将获取到的文章对象（post）传递给模板
    return render(request, 'blog/post_detail.html', {'post':post})

def post_create(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            new_post = form.save(commit=False)
            new_post.autor = request.user  # 假设用户已登录
            new_post.save()
            
            return redirect('blog:post_detail', post_id = new_post.id)
    else:
        form = PostForm()
        return render(request, 'blog/post_form.html', {'form': form})
    